/**
 * Created by xuelei.kong on 2017/4/18.
 */
//给数字字符串补零，不支持负数
function padNumber(num, fill) {
    var len = ('' + num).length;
    return (Array(
        fill > len ? fill - len + 1 || 0 : 0
    ).join(0) + num);
}
var utils = {
    winW: function () {
        return $(window).width();
    },
    sideBarW: function () {
        return $('.extend').width();
    },
    rightContentWidth: function () {
        // return this.winW() - this.sideBarW() - 8;
        return this.winW() - 58;
    },
    winResize: function (fn) {
        var timer;
        $(window).resize(function () {
            clearTimeout(timer);
            timer = setTimeout(function () {
                fn()
            }, 30);
        })
    }
};
console.log(utils.rightContentWidth());

var app = new Vue({
    el: '#app',
    data: function () {
        return {
            subChartTitle: "",
            dates: [],
            defaultBeginTime: "2017-04-01",
            defaultEndTime: "2017-04-01",
            multipleDeviceData: [],
            ztree: null,
            multiDate: [],
            isManyDeviceAndManyDate: false,
            showAddRangeBtn: false,
            compareDate: [],
            colors: [
                '0, 200, 255',
                '25, 255, 153',
                '255, 100, 0',
                '255, 0, 0',
                '0, 255, 0',
                '255, 51, 204',
                '204, 51, 51',
                '255, 153, 102'
            ],
            maxValue: 0,
            chartCurve: {},
            chartColumn: {},
            compareText: ['同环比', '自定义'],
            thbText: ['查询', '环比', '同比'],
            zdyCompareText: ['查询', '对比1', '对比2', '对比3'],
            finalSearchIndex: 0,
            curveColor: [
                // '#00c8ff',
                // '#00ff99',
                // '#ff6400',
                // '#ff0000',
                // '#00ff00',
                // '#ff33cc',
                // '#cc3333',
                // '#ff9966',
                '0, 200, 255',
                '25, 255, 153',
                '255, 100, 0',
                '255, 0, 0',
                '0, 255, 0',
                '255, 51, 204',
                '204, 51, 51',
                '255, 153, 102'
            ],
            columnColor: [
                '#00C8FF',
                '#04FA99',
                '#FF6400',
                '#fffc6d',
                '#DC55DD'
            ],
            compareType: 0,
            rangType: ['日', '月', '年'],
            rangTypeIndex: 0,
            loadingFlag: false,
            ztreeLoadingFlag: true,
            equipment: ['瑞必达能源管理平台'],
            equipmentID: [5067],
            compareEquipment: ['瑞必达能源管理平台'],
            moreDayArr: [1, 2, 3],
            moreMonthArr: [1, 2, 3],
            moreYearArr: [1, 2, 3],
            zdyDays: [],
            zdyMonths: [],
            zdyYears: [],
            thb: {
                day: {
                    from: '',
                    to: ''
                },
                month: {
                    from: '',
                    to: ''
                },
                year: {
                    from: '',
                    to: ''
                }
            },
            optional: {
                day: {
                    from: '',
                    to: ''
                },
                month: {
                    from: '',
                    to: ''
                },
                year: {
                    from: '',
                    to: ''
                }
            },
            // curveTitle:"设备A多时段负荷曲线",

            searchType: 0,


            //柱状图series
            /*columnSeries: [{
             name: '查询',
             data: [13, 4, 13, 5, 4, 10, 12, 4, 13, 5],
             color: '#00C8FF'
             // lineWidth: 1
             // lineColor: 'rgba(8, 135, 175, 1)',
             // fillColor: 'rgba(234, 61, 36, 1)'
             }, {
             name: '环比',
             data: [11, 3, 4, 13, 3, 15, 4, 13, 3, 15],
             color: '#04FA99'
             }, {
             name: '同比',
             data: [15, 3, 4, 23, 3, 5, 14, 3, 5, 14],
             color: '#FF6400'
             }],
             //柱状图categories
             columnCategories: [
             '2017.3.19',
             '2017.3.21',
             '2017.3.22',
             '2017.3.23',
             '2017.3.24',
             '2017.3.25',
             '2017.3.26',
             '2017.3.27',
             '2017.3.28',
             '2017.3.29'
             ]*/


        }
    },
    mounted: function () {
        //ztree
        var that = this;
        this.loadingFlag = true;

        $.ajax({
            url: "http://180.166.106.206:8086/Data/GetTree",
            type: 'GET',
            success: function (res) {
                console.log(res);
                var code;

                function setCheck() {
                    var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
                        py = $("#py").attr("checked") ? "p" : "",
                        sy = $("#sy").attr("checked") ? "s" : "",
                        pn = $("#pn").attr("checked") ? "p" : "",
                        sn = $("#sn").attr("checked") ? "s" : "",
                        // type = {"Y": py + sy, "N": pn + sn};
                        type = {"Y": "", "N": ""};

                    zTree.setting.check.chkboxType = type;
                    showCode('setting.check.chkboxType = { "Y" : "' + type.Y + '", "N" : "' + type.N + '" };');
                }

                function showCode(str) {
                    if (!code) code = $("#code");
                    code.empty();
                    code.append("<li>" + str + "</li>");
                }

                var setting = {
                    check: {
                        enable: true
                    },

                    data: {
                        simpleData: {
                            enable: true
                        }
                    },

                    view: {
                        fontCss: setHighlight // 高亮一定要设置，setHighlight是自定义方法
                    },

                    callback: {
                        onCheck: onCheck
                    }
                };
                that.ztree = $.fn.zTree.init($("#treeDemo"), setting, res.zNodes);
                that.ztreeLoadingFlag = false;

                var node = that.ztree.getNodeByParam("id", res.zNodes[0].id);
                that.ztree.checkNode(node);
                // 设置高亮字体
                function setHighlight(treeId, treeNode) {
                    console.log(treeNode);
                    return (treeNode.highlight) ? {
                        color: "#EB6100"
                        // "font-weight": "bold",
                        // "background-color": "#EB6100"
                    } : {color: "#01fcf0", "font-weight": "normal"};
                }


                // var node = zTree.getNodeByParam("id",5001);
                // zTree.selectNode(node);

                setCheck();
                $("#py").bind("change", setCheck);
                $("#sy").bind("change", setCheck);
                $("#pn").bind("change", setCheck);
                $("#sn").bind("change", setCheck);

                function onCheck(e, treeId, treeNode) {
                    var treeObj = $.fn.zTree.getZTreeObj("treeDemo"),
                        nodes = treeObj.getCheckedNodes(true),
                        v = "";
                    that.equipment = [];
                    that.equipmentID = [];
                    for (var i = 0; i < nodes.length; i++) {
                        v += nodes[i].name + ",";
                        console.log(nodes[i]);
                        // alert(nodes[i].id); //获取选中节点的值
                        if (!nodes[i].children) {

                        }
                        that.equipmentID.push(nodes[i].id);
                        that.equipment.push(nodes[i].name);

                    }
                    if (/*that.equipmentID.length === 1 &&*/ that.compareType === 1) {

                        if ((that.moreDayArr.length && that.rangTypeIndex === 0)
                            || (that.moreMonthArr.length && that.rangTypeIndex === 1)
                            || (that.moreYearArr.length && that.rangTypeIndex === 2)
                        ) {
                            that.showAddRangeBtn = true;
                        }
                    } else {
                        // that.showAddRangeBtn = false;
                        // $('.more-range').empty();
                        that.moreDayArr = [1, 2, 3];
                        that.moreMonthArr = [1, 2, 3];
                        that.moreYearArr = [1, 2, 3];
                    }
                    console.log(that.equipmentID);


                }

                // that.drawChart();

            }

        });

        that.search();


    },
    methods: {
// 模糊搜索name满足条件的节点
        searchNode: function () {
            var value=this.$refs.ztreesearch.value;
            if (value == "") return;

            // 获取搜索的节点
            var nodes = this.ztree.getNodesByParamFuzzy("name", value);
            // 关闭所有节点的高亮
            var allNodes = this.ztree.transformToArray(this.ztree.getNodes());
            for (var i = 0; i < allNodes.length; i++) {
                allNodes[i].highlight = false;
                this.ztree.updateNode(allNodes[i]);
            }
            // 展开第一层节点
            this.ztree.expandAll(false);
            this.ztree.expandNode(this.ztree.getNodes()[0], true);
            // 高亮并展开搜索到的节点
            for (var i = 0; i < nodes.length; i++) {
                nodes[i].highlight = true;
                this.ztree.updateNode(nodes[i]); // 更新节点，让高亮生效
                this.ztree.expandNode(nodes[i].getParentNode(), true);
            }
        },
        searchNodeLazy: function () {
            var timeoutId = null;
            var that=this;
            var value = event.target.value;
            if (timeoutId) {
                console.log(222);
                clearTimeout(timeoutId);
            }
            timeoutId = setTimeout(function () {
                console.log(111);
                that.searchNode(value);
            }, 500);
        },
        changeCompareType: function (idx) {
            this.compareType = idx;

            if (this.compareType === 0) {
                this.showAddRangeBtn = false;
                this.zdyDays = [];
                $('.more-range').empty();
                this.moreDayArr = [1, 2, 3];
                this.moreMonthArr = [1, 2, 3];
                this.moreYearArr = [1, 2, 3];
            } else {
                this.showAddRangeBtn = true;
            }


            if (this.equipmentID.length === 1 && this.compareType === 1) {
                // this.showAddRangeBtn = true;
            }

        },
        //切换时间区间颗粒度
        changeRangType: function (idx) {
            this.rangTypeIndex = idx;

            if ((!this.moreDayArr.length && this.rangTypeIndex === 0) || (!this.moreMonthArr.length && this.rangTypeIndex === 1) || (!this.moreYearArr.length && this.rangTypeIndex === 2)) {
                this.showAddRangeBtn = false;
            } else {
                if (this.compareType === 1) {
                    this.showAddRangeBtn = true;

                }
            }
        },

        //查询方法
        search: function () {
            var that = this;
            var begin = $('#datePickerBox' + this.rangTypeIndex).find('.from').val();
            var end = $('#datePickerBox' + this.rangTypeIndex).find('.to').val();
            that.finalSearchIndex = that.rangTypeIndex;
            that.compareDate = [];
            that.loadingFlag = false;
            // return;

            //同环比
            if (!this.equipmentID.length) {
                alert('请选择设备');
                return;
            }
            this.compareDate = [];
            if (this.compareType === 0) {

                if (this.equipmentID.length > 1) {
                    alert("同环比只支持单设备查询");
                    return;
                }

                if (begin === '' || end === '') {
                    alert('请选择时间段');
                } else {
                    this.isManyDeviceAndManyDate = false;
                    this.dates = [];
                    switch (this.rangTypeIndex) {
                        case 0:
                            var Syear = parseFloat(begin.split('-')[0]);
                            var Eyear = parseFloat(end.split('-')[0]);
                            var Smonth = parseFloat(begin.split('-')[1]);
                            var Emonth = parseFloat(end.split('-')[1]);
                            var Sday = parseFloat(begin.split('-')[2]);
                            var Eday = parseFloat(end.split('-')[2]);
                            this.compareDate.push(
                                begin + '至' + end,
                                (Syear - 1) + "-" + padNumber(Smonth, 2) + "-" + padNumber(Sday, 2) + "至" + padNumber(Eyear - 1, 2) + "-" + padNumber(Emonth, 2) + "-" + padNumber(Eday, 2),
                                Syear + '-' + padNumber(Smonth - 1, 2) + '-' + padNumber(Sday, 2) + '至' + Eyear + '-' + padNumber(Emonth - 1, 2) + '-' + padNumber(Eday, 2)
                            );
                            break;
                        case 1:
                            var Syear = Number(begin.replace(/[\u4e00-\u9fa5]+/g, ' ').split(' ')[0]);
                            var Eyear = Number(end.replace(/[\u4e00-\u9fa5]+/g, ' ').split(' ')[0]);
                            var Smonth = Number(begin.replace(/[\u4e00-\u9fa5]+/g, ' ').split(' ')[1]);
                            var Emonth = Number(end.replace(/[\u4e00-\u9fa5]+/g, ' ').split(' ')[1]);
                            this.compareDate.push(
                                begin + '至' + end,
                                (Syear - 1) + "年" + Smonth + "月至" + (Eyear - 1) + "年" + Emonth + "月",
                                Syear + "年" + (Smonth - 1) + "月至" + Eyear + "年" + (Emonth - 1) + "月"
                            );
                    }

                    console.log(this.dates);

                    //同环比
                    this.loadingFlag = true;
                    $.ajax({
                        url: "http://180.166.106.206:8086/Data/SearchPrevAndLast",
                        type: 'GET',
                        data: {
                            id: that.equipmentID.join(','),
                            type: that.rangTypeIndex + 2,
                            begin: begin.split('-').join('.'),
                            end: end.split('-').join('.')
                        },
                        // timeOut: 10000,
                        // error: function (XMLHttpRequest, textStatus, errorThrown) {
                        //     //TODO: 处理status， http status code，超时 408
                        //     // 注意：如果发生了错误，错误信息（第二个参数）除了得到null之外，还可能
                        //     //是"timeout", "error", "notmodified" 和 "parsererror"。
                        //     console.log(textStatus);
                        // },
                        success: function (res) {
                            // that.getSearchType();
                            that.searchType = 0;
                            that.subChartTitle = '设备' + that.equipment[0] + '同环比用能对比';
                            that.multiDate = [res.List];
                            $('.container-wrapper').animate({
                                scrollTop: 0
                            }, 300);
                            $('.table-box').width('100%');
                            // $('.table-box').width(res.List.length * 350 + 50);
                            //找出最大值
                            var max = [];
                            $.each(res.List, function (i, item) {
                                max.push(Math.max.apply(null, item.Values))
                            });
                            // console.log(eachMax);
                            that.maxValue = [Math.max.apply(null, max) + Math.max.apply(null, max) * 0.1];

                            //时间轴
                            that.curveCategories = that.columnCategories = (function () {
                                var arr = [];


                                //TODO 时间段显示
                                function getDur() {
                                    return (function () {
                                        var t = new Date(end).getTime() - new Date(begin).getTime() - 24 * 60 * 60 * 1000;
                                        if (t < 0) {
                                            '一天时间段';
                                        } else {
                                            '大于一天';
                                        }
                                    })();
                                }

                                $.each(res.List[0].Labels, function (i, item) {
                                    if (item.split(' ').length === 1) {
                                        arr.push(item.split('/')[1]);

                                    } else {
                                        arr.push(item.split(' ')[1]);
                                    }
                                });

                                return arr;
                            })();

                            that.curveSeries = that.columnSeries = [];
                            for (var i = 0; i < res.List.length; i++) {
                                console.log(that.curveColor[i]);
                                that.curveSeries.push({
                                    data: res.List[i].Values,
                                    name: that.compareDate[i],
                                    color: 'rgba(' + that.curveColor[i] + ',1)',
                                    lineWidth: 1,
                                    lineColor: 'rgba(' + that.curveColor[i] + ',1)',
                                    fillColor: 'rgba(' + that.curveColor[i] + ',0.5)'
                                });
                            }

                            that.drawChart();
                            that.loadingFlag = false;

                        }
                    });
                }
            } else if (this.compareType === 1) {
                //自定义
                var flag = true;
                $('#datePickerBox' + this.rangTypeIndex).find('input').each(function (i, item) {
                    console.log(item);
                    var val = $(this).val();
                    if (val === '') {
                        flag = false;
                        return false;
                    }
                });

                if (!flag) {
                    alert('请选择时间段');
                    return;
                }

                this.loadingFlag = true;
                // http://180.166.106.206:8086/Data/SearchManyDate?id=5001&begin=2017.1.1&end=2017.1.7&begin=2017.1.8&end=2017.1.14
                function isSingleDate() {
                    switch (that.rangTypeIndex) {
                        case 0:
                            if (that.moreDayArr.length === 3) {
                                return true;
                            }
                            break;
                        case 1:
                            if (that.moreMonthArr.length === 3) {
                                return true;
                            }
                            break;
                        case 2:
                            if (that.moreYearArr.length === 3) {
                                return true;
                            }
                    }
                }

                if (isSingleDate()) {
                    that.isManyDeviceAndManyDate = false;
                    // alert('多设备或单设备---单时间');
                    //多设备或单设备---单时间
                    var equipmentParam = (function () {
                        var param = '';
                        for (var i = 0; i < that.equipmentID.length; i++) {
                            param += '&id=' + that.equipmentID[i];

                        }
                        return param.replace('&', '?');
                    })();

                    $.ajax({
                        url: "http://180.166.106.206:8086/Data/SearchManyDevice" + equipmentParam,
                        type: 'GET',
                        data: {
                            type: that.rangTypeIndex + 2,
                            begin: begin.split('-').join('.'),
                            end: end.split('-').join('.')
                        },
                        success: function (res) {
                            that.compareDate = [begin + '至' + end];

                            that.compareEquipment = that.equipment;
                            $('.container-wrapper').animate({
                                scrollTop: 0
                            }, 300);
                            // $('.table-box').width(res.List.length * 350 + 50);
                            //找出最大值
                            var max = [];
                            $.each(res.List, function (i, item) {
                                max.push(Math.max.apply(null, item.Values))
                            });
                            // console.log(eachMax);
                            that.maxValue = [Math.max.apply(null, max) + Math.max.apply(null, max) * 0.1];


                            if (that.equipment.length === 1) {
                                that.searchType = 1;
                                // alert('单设备，单时间');
                                that.subChartTitle = '设备' + that.equipment[0] + '单时段用能';
                                that.multiDate = [res.List];
                                // that.multiDate = [res.List];

                            } else {
                                // alert('多设备，单时间');
                                that.searchType = 2;
                                that.subChartTitle = '设备' + that.equipment.join(',') + '单时段用能';
                                // that.isManyDeviceAndManyDate = true;

                                that.multiDate = res.List;
                                $('.table-box').width(res.List.length * 350 + 50);
                                //找出最大值
                                var eachMax = [];
                                $.each(res.List, function (i, item) {
                                    eachMax.push(Math.max.apply(null, item.Values) + Math.max.apply(null, item.Values) * 0.1)
                                });
                                that.maxValue = eachMax;
                                // that.loadingFlag=false;
                                // return;
                            }

                            that.curveCategories = that.columnCategories = res.List[0].Labels;
                            that.curveSeries = that.columnSeries = [];
                            for (var i = 0; i < res.List.length; i++) {
                                console.log(that.curveColor[i]);

                                that.curveSeries.push({
                                    data: res.List[i].Values,
                                    name: that.equipment[i],
                                    color: 'rgba(' + that.curveColor[i] + ',1)',
                                    lineWidth: 1,
                                    lineColor: 'rgba(' + that.curveColor[i] + ',1)',
                                    fillColor: 'rgba(' + that.curveColor[i] + ',0.5)'
                                });
                            }

                            that.drawChart();
                            that.loadingFlag = false;
                        }
                    })

                } else {
                    that.isManyDeviceAndManyDate = false;
                    //单设备 多时间段

                    // http://180.166.106.206:8086/Data/SearchManyDate?id=5001&begin=2017.1.1&end=2017.1.7&begin=2017.1.8&end=2017.1.14

                    if (this.equipment.length === 1) {
                        var dateParam = (function () {
                            var param = '';
                            $('#datePickerBox' + that.rangTypeIndex).find('.more-item').each(function (i, item) {
                                console.log(item);
                                param += '&begin=' + $(item).find(".from").val().split('-').join('.') + '&end=' + $(item).find('.to').val().split('-').join('.');

                                that.compareDate.push($(item).find(".from").val() + '至' + $(item).find('.to').val());
                            });
                            return param;
                            // return param.replace('&', '?');
                        })();

                        $.ajax({
                            url: 'http://180.166.106.206:8086/Data/SearchManyDate?id=' + that.equipmentID[0] + dateParam,
                            data: {
                                type: that.rangTypeIndex + 2
                            },
                            type: 'GET',
                            success: function (res) {
                                console.log(res);
                                //单设备 多时间段
                                that.searchType = 3;
                                $('.container-wrapper').animate({
                                    scrollTop: 0
                                }, 300);
                                // alert('单设备 多时间段');
                                that.multiDate = [res.List];
                                that.compareEquipment = that.equipment;
                                // $('.table-box').width(res.List.length * 350 + 50);
                                //找出最大值
                                var max = [];
                                $.each(res.List, function (i, item) {
                                    max.push(Math.max.apply(null, item.Values))
                                });
                                // console.log(eachMax);
                                that.maxValue = [Math.max.apply(null, max) + Math.max.apply(null, max) * 0.1];
                                that.subChartTitle = '设备' + that.equipment[0] + '多时段用能';
                                that.curveCategories = that.columnCategories = (function () {
                                    var arr = [];
                                    $.each(res.List[0].Labels, function (i, item) {
                                        arr.push(item.split(' ')[1]);
                                    });
                                    return arr;
                                })();
                                that.curveSeries = that.columnSeries = [];
                                for (var i = 0; i < res.List.length; i++) {
                                    console.log(that.curveColor[i]);
                                    var name = i === 0 ? '查询' : '对比' + i;
                                    that.curveSeries.push({
                                        data: res.List[i].Values,
                                        name: that.compareDate[i],
                                        color: 'rgba(' + that.curveColor[i] + ',1)',
                                        lineWidth: 1,
                                        lineColor: 'rgba(' + that.curveColor[i] + ',1)',
                                        fillColor: 'rgba(' + that.curveColor[i] + ',0.5)'
                                    });
                                }


                                that.drawChart();


                                that.loadingFlag = false;

                            }
                        });
                    } else {
                        // alert('多设备多时间段')
                        //多设备多时间段 接口  http://180.166.106.206:8086/Data/SearchManyDeviceDate?mid=5001&mid=5012&begin=2017.1.1&end=2017.1.7&begin=2017.1.8&end=2017.1.14

                        that.isManyDeviceAndManyDate = true;
                        var dateParam = (function () {
                            var param = '';
                            $('#datePickerBox' + that.rangTypeIndex).find('.more-item').each(function (i, item) {
                                console.log(item);
                                param += '&begin=' + $(item).find(".from").val().split('-').join('.') + '&end=' + $(item).find('.to').val().split('-').join('.');
                            });
                            return param;
                            // return param.replace('&', '?');
                        })();
                        var equipmentParam = (function () {
                            var param = that.equipmentID.join('&mid=');
                            return param;
                        })();
                        console.log(equipmentParam);
                        that.compareEquipment = that.equipment;
                        that.compareDate = [];
                        $('#datePickerBox' + that.rangTypeIndex).find('.more-item').each(function (i, item) {
                            console.log(item);
                            // compareDate += '&begin=' + $(item).find(".from").val().split('-').join('.') + '&end=' + $(item).find('.to').val().split('-').join('.');
                            that.compareDate.push($(item).find(".from").val() + '至' + $(item).find('.to').val());
                        });
                        $.ajax({
                            url: 'http://180.166.106.206:8086/Data/SearchManyDeviceDate?mid=' + equipmentParam + dateParam,
                            data: {
                                type: that.rangTypeIndex + 2
                            },
                            type: 'GET',
                            success: function (res) {
                                $('.container-wrapper').animate({
                                    scrollTop: 403
                                }, 300);
                                that.searchType = 4;
                                console.log(res);
                                that.multipleDeviceData = res.DataList;
                                $('.table-box').width(res.DataList.length * 350 + 50);
                                //找出最大值
                                var eachMax = [];
                                $.each(res.DataList, function (i, item) {
                                    var max = [];
                                    $.each(item.List, function (j, list) {
                                        max.push(Math.max.apply(null, list.Values));
                                    });
                                    eachMax.push(Math.max.apply(null, max) + Math.max.apply(null, max) * 0.1)
                                });
                                that.maxValue = eachMax;
                                that.loadingFlag = false;
                                that.resetSearch();

                            }
                        });
                    }


                }

                // that.resetSearch();
            }

        },
        getTime: function (unit) {
            if (unit.split(' ').length === 1) {
                return unit.split('/')[1];

            } else {
                return unit.split(' ')[1];
            }
        },
        bgColor: function (index) {

            return 'background-color:rgb(' + this.colors[index] + ')';
        },
        fontColor: function (index) {
            if (this.searchType === 2) {
                return 'color:rgb(255,255,255)';
            }
            return 'color:rgb(' + this.colors[index] + ')';
        },
        getWidth: function (W, index, k) {
            return 'width:' + (W === 0 ? 0 : W / this.maxValue[index]) * 100 + '%;background:rgb(' + this.colors[k] + ')'
        },
        setDatePickerVmodel: function (type) {
            this[type] = event.target.value;
        },
        getSearchType: function () {
            if (this.compareType === 0) {
                //同环比
                return this.searchType = 0;

            } else if (this.compareType === 1) {
                if ((this.moreDayArr.length === 3 && this.rangTypeIndex === 0) ||
                    (this.moreMonthArr.length === 3 && this.rangTypeIndex === 1) ||
                    (this.moreYearArr.length === 3 && this.rangTypeIndex === 2)) {
                    if (this.equipment.length === 1) {
                        //单设备单时段
                        return this.searchType = 1;
                    } else {
                        //多设备单时段
                        return this.searchType = 2;
                    }

                } else {
                    if (this.equipment.length === 1) {
                        //单设备多时段
                        return this.searchType = 3;
                    } else {
                        //多设备多时段
                        return this.searchType = 4;
                    }
                }

            }
        },
        compareTitle: function () {
            if (this.compareType === 0) {
                //同环比
                return '同环比';
            } else {
                if (
                    (this.moreDayArr.length === 3 && this.rangTypeIndex === 0) ||
                    (this.moreMonthArr.length === 3 && this.rangTypeIndex === 1) ||
                    (this.moreYearArr.length === 3 && this.rangTypeIndex === 2)
                ) {

                    return "单时段";

                } else {
                    this.resetSearch();
                    return '多时段'
                }
            }

        },
        drawChart: function () {
            var that = this;
            //折线图
            this.chartCurve = new Highcharts.Chart('chart1', {
                chart: {
                    type: 'areaspline',
                    backgroundColor: "rgba(12, 35, 42, 0)",
                    // borderColor: "#28c6de",
                    // borderRadius: "4",
                    // borderWidth: "0.5",
                    // marginLeft: 40,
                    marginRight: 50,
                    // marginTop: 55,
                    // marginBottom:-30,
                    // width: utils.rightContentWidth() * 0.7,
                    // height: rightHeight * 0.441,
                    zoomType: 'x'
                },
                title: {
                    text: this.equipment.join(',') + this.compareTitle() + '曲线',
                    style: {
                        color: '#35ffea',
                        fontSize: "18px"
                    },
                    y: 25
                },
                legend: {
                    padding: 10,
                    enabled: true,
                    layout: 'horizontal',
                    align: 'right',
                    verticalAlign: 'top',
                    x: -50,
                    y: 30,
                    border: 'none',
                    //floating: true,
                    itemStyle: {
                        color: "#fff"
                    },
                    itemHoverStyle: {
                        color: '#fd4c01'
                    }
                    // backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'
                },
                xAxis: {
                    min: 0,
                    crosshair: true,
                    lineColor: '#65B28C',
                    // type: 'datetime',
                    labels: {
                        style: {
                            color: '#fff'
                        }
                    },
                    categories: that.curveCategories
                },
                yAxis: {
                    "gridLineColor": '#78888a',
                    labels: {
                        style: {
                            color: '#fff'
                        }
                    },
                    title: {
                        text: ''
                    }
                },
                tooltip: {
                    shared: true,
                    // valueSuffix: ' ',
                    backgroundColor: '#000',
                    borderColor: '#01fcf0',
                    style: {
                        color: '#19ff86'
                    },

                    useHtml: true,
                    headerFormat: '',
                    pointFormatter: function () {
                        return '<div><p style="line-height:200%;"><span style="color: ' + this.series.color + '">时刻：' + parseInt(this.x + 1) + ' </span></p><br><br><br>' +
                            '<p><span style="text-align:right;color:' + this.series.color + '">负荷：' + this.y + ' KWH</span></p><br></div>';
                    }
                },
                credits: {
                    enabled: false
                },
                plotOptions: {
                    areaspline: {
                        fillOpacity: 0.5
                    }
                },
                series: this.curveSeries
            });
            //that.resetSearch();
            //柱状图
            /*console.log(this.columnCategories);
             this.chartColumn = new Highcharts.Chart('chart3', {
             chart: {
             type: 'bar',
             width: utils.rightContentWidth() - 30,
             height: this.columnSeries.length * 20 * this.columnCategories.length,
             backgroundColor: "rgba(12, 35, 42, 0)"
             },
             title: {
             text: ''
             },
             subtitle: {
             text: ''
             },
             xAxis: {
             categories: this.columnCategories,
             labels: {
             style: {
             color: '#fff'
             }
             },
             title: {
             text: null
             }
             },
             yAxis: {
             min: 0,
             title: {
             text: '',
             align: 'high'
             },
             labels: {
             style: {
             color: '#fff'
             },
             overflow: 'justify'
             }
             },
             tooltip: {
             valueSuffix: ''
             },
             plotOptions: {
             bar: {
             pointWidth: 10,
             dataLabels: {
             enabled: true,
             allowOverlap: true
             }
             }
             },
             legend: {
             // adjustChartSize: true,
             layout: 'vertical',
             align: 'right',
             verticalAlign: 'top',
             x: -40,
             y: 100,
             floating: true,
             borderWidth: 1,
             backgroundColor: ((Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'),
             shadow: true
             },
             credits: {
             enabled: false
             },
             series: this.columnSeries
             });*/


        },
        resetSearch: function () {
            this.moreYearArr = [1, 2, 3];
            this.moreDayArr = [1, 2, 3];
            this.moreMonthArr = [1, 2, 3];
            this.showAddRangeBtn = true;
            $('.more-range').empty();
        },
        addRange: function () {

            if (this.rangTypeIndex === 0) {
                $('.day-more-range').append($('#moreDay' + this.moreDayArr[0]).text());
                this.moreDayArr.splice(0, 1);
                if (!this.moreDayArr.length) {
                    this.showAddRangeBtn = false;
                }

            } else if (this.rangTypeIndex === 1) {
                $('.month-more-range').append($('#moreMonth' + this.moreMonthArr[0]).text());
                this.moreMonthArr.splice(0, 1);
                if (!this.moreMonthArr.length) {
                    this.showAddRangeBtn = false;
                }
            } else {
                $('.year-more-range').append($('#moreYear' + this.moreYearArr[0]).text());
                this.moreYearArr.splice(0, 1);
                if (!this.moreYearArr.length) {
                    this.showAddRangeBtn = false;
                }
            }


        }

    }

    /*,
     directives: {
     onlynumber: {
     bind: function (el, binding) {
     el.handler = function () {
     //el.value = el.value.replace(/\D+/, '')
     // console.log(el);
     console.log(0);
     }.bind(el);
     el.addEventListener('change', el.handler)
     },
     unbind: function () {
     el.removeEventListener('change', el.handler)
     }
     }
     }*/

});

/*$('.extend-btn').click(function () {
 $('body').toggleClass('extended');
 // app.$data.chartCurve.update({
 //     chart: {
 //         width: utils.rightContentWidth() * 0.7
 //     }
 // });
 //
 // app.$data.chartColumn.update({
 //     chart: {
 //         width: utils.rightContentWidth() - 30
 //     }
 // });
 });*/
$('.extend').hover(function () {
    $('body').toggleClass('extended');

});



var datePicker = {
    day: $('#textarea-day').text(),
    week: $('#textarea-week').text(),
    month: $('#textarea-month').text(),
    year: $('#textarea-year').text(),
    rang: $('#textarea-rang').text()
};


//移除添加的时间段
var removeRangeItem = function (idx) {
    $('#datePickerBox' + app.$data.rangTypeIndex).find('.more-item' + idx).remove();
    if (app.$data.rangTypeIndex === 0) {
        app.$data.moreDayArr.push(idx);
    } else if (app.$data.rangTypeIndex === 1) {
        app.$data.moreMonthArr.push(idx);
    } else {
        app.$data.moreYearArr.push(idx);
    }

    if ((app.$data.moreDayArr.length && app.$data.rangTypeIndex === 0)
        || (app.$data.moreMonthArr.length && app.$data.rangTypeIndex === 1)
        || (app.$data.moreYearArr.length && app.$data.rangTypeIndex === 2)
    ) {
        app.$data.showAddRangeBtn = true;
    }
};





